package com.example.lexiangbackend.controller;

import com.example.lexiangbackend.entity.User;
import com.example.lexiangbackend.service.AuthService;
import com.example.lexiangbackend.dto.AuthResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/auth")
@CrossOrigin(origins = "http://localhost:8080")
public class AuthController {

    @Autowired
    private AuthService authService;

    /**
     * 验证token（通用接口）
     */
    @PostMapping("/verify-token")
    public ResponseEntity<AuthResponse> verifyToken(@RequestParam String token) {
        try {
            User user = authService.verifyToken(token);
            // 从token中提取角色信息
            String role = authService.extractRoleFromToken(token);
            return ResponseEntity.ok(new AuthResponse(true, "Token有效", token, role, user));
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                    .body(new AuthResponse(false, "Token无效", null, null, null));
        }
    }

    /**
     * 刷新token（通用接口）
     */
    @PostMapping("/refresh-token")
    public ResponseEntity<AuthResponse> refreshToken(@RequestParam String token) {
        try {
            // TODO: 实现token刷新逻辑
            return ResponseEntity.ok(new AuthResponse(true, "功能开发中", null, null, null));
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                    .body(new AuthResponse(false, "Token刷新失败", null, null, null));
        }
    }

    /**
     * 退出登录（通用接口）
     */
    @PostMapping("/logout")
    public ResponseEntity<AuthResponse> logout(@RequestParam String token) {
        try {
            // TODO: 实现退出登录逻辑（可以将token加入黑名单）
            return ResponseEntity.ok(new AuthResponse(true, "退出成功", null, null, null));
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                    .body(new AuthResponse(false, "退出失败", null, null, null));
        }
    }

    @GetMapping("/test")
    public ResponseEntity<String> testConnection() {
        return ResponseEntity.ok("后端连接正常 - 乐享作坊API服务运行中");
    }
} 